import React from 'react';
import {getProductCategories} from '../api';
import styles from '../style.css';
import PropTypes from 'prop-types';
import {injectIntl, formatMessage} from '../intl';
import SelectAlert from '../../common/SelectAlert';
import SeniorModal from '../../common/SeniorModal';
import TextInput from 'Shared/components/TextInput';
import {conventSorter} from '../utils';
import {Row, Col, Form, Button, Divider, Table, message as msg} from 'antd';
import {PAGE, TABLE, PAGINATION_OPTIONS, FORM_OPTIONS,
    COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, ROWSELECTION_FIXED_COLUMN_WIDTH} from '../../constants';
class ProductCategoryPanel extends React.PureComponent {
    state = {
        code: '',
        name: '',
        data: {},
        message: '',
        selectedRows: [],
        isFetching: false,
        selectedRowKeys: [],
        currentCondition: {},
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize
    }
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = {...this.state.currentCondition};
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: pagination.current - 1
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    }
    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }
    onQuery = condition => {
        this.setState({isFetching: true});
        getProductCategories(condition)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        message: '',
                        data: res.data,
                        currentCondition: condition
                    });
                else
                    this.setState({
                        isFetching: false,
                        data: [],
                        message: res.message
                    });
            });
    }

    onClickSearchBtn = () => {
        const condition = {
            type: 2,
            isAll: true,
            code: this.state.code,
            name: this.state.name,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        this.onQuery(condition);
    }

    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }

    onChange = (value, name) => {
        this.setState({[name]: value});
    }
    onClickReset = () => {
        this.setState({
            code: '',
            name: ''
        });
    }
    onChangeRadio = (selectedRowKeys, selectedRows) => {
        this.setState({
            selectedRowKeys,
            selectedRows
        });
        this.props.onSelect(selectedRows[0]);
    }

    onCloseTag = () => {
        this.setState({
            selectedRowKeys: [],
            selectedRows: []
        });
    }
    onSubmit = () => {
        if(!this.state.selectedRows.length)
            return msg.warn(formatMessage({
                id: 'productCategoryPanel.validate.part',
                defaultMessage: '请选择产品信息'
            }));
        this.props.onSelect(this.state.selectedRows[0]);
    }
    render() {
        const {isFetching, data, message} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const columns = [
            {
                title: formatMessage({
                    id: 'productCategoryPanel.code',
                    defaultMessage: '车型编号'
                }),
                dataIndex: 'code',
                sorter: true,
            },
            {
                title: formatMessage({
                    id: 'productCategoryPanel.name',
                    defaultMessage: '车型名称'
                }),
                dataIndex: 'name',
            },
            {
                title: formatMessage({
                    id: 'productCategoryPanel.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark',
            },
        ];
        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const onRow = record => ({
            onDoubleClick: () => {
                // 双击选中
                this.props.onSelect(record[0]);
            }
        });
        return (
            <SeniorModal
                title={formatMessage({
                    id: 'productCategoryPanel.show.title',
                    defaultMessage: '产品分类查询'
                })}
                width="60%"
                maskClosable={false}
                footer={null}
                destroyOnClose={true}
                wrapClassName={styles.dataSelectModal}
                visible={true}
                onCancel={this.props.onCancel}>
                <Row className="form-standard">
                    <Col {...FORM_OPTIONS.col}>
                        <Form.Item label={formatMessage({
                            id: 'productCategoryPanel.code',
                            defaultMessage: '车型编号'
                        })} {...FORM_OPTIONS.item}>
                            <TextInput
                                allowClear
                                name="code"
                                value={this.state.code}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </Form.Item>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <Form.Item label={formatMessage({
                            id: 'productCategoryPanel.name',
                            defaultMessage: '车型名称'
                        })} {...FORM_OPTIONS.item}>
                            <TextInput
                                allowClear
                                name="name"
                                value={this.state.name}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </Form.Item>
                    </Col>
                    <Col {...FORM_OPTIONS.col} className={styles['inline-button']}>
                        <Button
                            type="primary"
                            loading={isFetching}
                            onClick={this.onClickSearchBtn}>
                            {formatMessage({
                                id: 'productCategoryPanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                        <Button key="clear" onClick={this.onClickReset}>{formatMessage({
                            id: 'productCategoryPanel.btn.reset',
                            defaultMessage: '重置'
                        })}</Button>
                    </Col>
                </Row>
                <Divider className={styles.divider}/>
                <SelectAlert data={this.state.selectRows}
                    onConfirm={this.onSubmit}
                    onDelete={this.onCloseTag}/>
                <Table
                    className="white-space-nowrap"
                    rowKey="id"
                    dataSource={data.content}
                    rowClassName={styles.tableCursor}
                    columns={columns}
                    onRow={this.props.type ? onRow : () => ''}
                    loading={isFetching}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    rowSelection={{
                        type: 'radio',
                        fixed: true,
                        columnWidth: ROWSELECTION_FIXED_COLUMN_WIDTH,
                        onChange: this.onChangeRadio,
                        selectedRowKeys: this.state.selectedRowKeys,
                        getCheckboxProps: record => ({
                            disabled: this.props.currentSelectRowkeys === record.id
                        })}}
                    {...TABLE}
                    locale={{
                        emptyText: message ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
                    }} />
            </SeniorModal >
        );
    }
}

ProductCategoryPanel.propTypes = {
    onSelect: PropTypes.func.isRequired,
    currentSelectRowkeys: PropTypes.string,
    type: PropTypes.string,
    onCancel: PropTypes.func,
};
export default injectIntl(ProductCategoryPanel);
